package com.chen.demo02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

// 线程创建方式三：实现callable接口
public class TestCallable implements Callable<Boolean> {

    private String url;
    private String name;

    public TestCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载的文件名：" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("http://www.apache.org/events/current-event-125x125.png", "1.jpg");
        TestCallable t2 = new TestCallable("https://www.baidu.com/img/flexible/logo/pc/result.png", "2.jpg");
        TestCallable t3 = new TestCallable("https://portrait.gitee.com/uploads/avatars/user/136/409700_younger11_1579401423.png!avatar60", "3.jpg");

        // 创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);

        // 提交执行
        Future<Boolean> rs1 = ser.submit(t1);
        Future<Boolean> rs2 = ser.submit(t2);
        Future<Boolean> rs3 = ser.submit(t3);

        // 获取结果
        Boolean result1 = rs1.get();
        Boolean result2 = rs2.get();
        Boolean result3 = rs3.get();

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);

        // 关闭服务
        ser.shutdown();


    }

}
// 下载器
class WebDownloader{
    public void downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");
        }
    }
}